package club.itstudio.itouc.controller.jw

import club.itstudio.itouc.core.exception.ITOUCException
import club.itstudio.itouc.core.util.Result
import club.itstudio.itouc.core.util.ResultUtil
import club.itstudio.itouc.service.JwOps
import club.itstudio.itouc.util.Mysql
import club.itstudio.itouc.util.Redis
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController

@RestController
class SpecialtyList(val jwOps: JwOps,
                    val redis: Redis,
                    val mysql: Mysql){
    /**
     * 获取指定年份的专业列表
     * @param grade: 年份
     */
    @GetMapping("/jw/specialty/{grade}")
    fun specialtyList(@PathVariable grade: String): Result<Any> {
        val list = try {    // 从redis中获取
            redis.getSpecialtyList(grade)
        }catch (e: ITOUCException) {
            try {   // 从数据库获取
                val list = mysql.getSpecialtyList(grade)
                // 保存到redis
                redis.saveSpecialtyList(grade, list)
            }catch (e: ITOUCException) {
                // 从教务系统获取
                val list = jwOps.getSpecialtyList(grade)
                // 持久化mysql, redis
                mysql.saveSpecialtyList(grade, list)
                redis.saveSpecialtyList(grade, list)
            }
        }
        return ResultUtil.success(list)
    }
}